package com.zlyx.easy.mybatis.interceptors;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.tool.BaseType;
import com.zlyx.easy.database.interceptors.AbstractResultSetInterceptor;
import com.zlyx.easy.database.local.ReturnType;

/**
 * @Auth 赵光
 * @Describle
 * @2019年1月14日 下午12:28:08
 */
@Component
@Intercepts({ @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = { Statement.class }) })
public class ResultSetInterceptor extends AbstractResultSetInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		ResultSetHandler resultSetHandler = (ResultSetHandler) invocation.getTarget();
		Field resultField = resultSetHandler.getClass().getDeclaredField("mappedStatement");
		resultField.setAccessible(true);
		Class<?> resultType = ReturnType.getType();
		if (resultType != null && !BaseType.isJavaType(resultType)) {
			Statement statement = (Statement) invocation.getArgs()[0];
			try (ResultSet resultSet = statement.getResultSet()) {
				if (resultType != null) {
					return getResults(resultType, resultSet);
				}
			} catch (Exception e) {
				Logger.err(e);
			}
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		if (target instanceof ResultSetHandler) {
			return Plugin.wrap(target, this);
		} else {
			return target;
		}
	}

	@Override
	public void setProperties(Properties properties) {
		String dialect = properties.getProperty("dialect");
		Logger.info("mybatis intercept dialect:{}", dialect);
	}

}